<?php

namespace Drupal\shusy_product\Entity;

use Drupal\shusy_product\ViewsController\Traits\ShusyProductStatusTrait;
use Entity;
use EntityFieldQuery;

class ShusyProduct extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $name;

  public $info;

  public $vip = 1;

  public $summary;

  public $sort = 0;

  public $status = 0;

  use ShusyProductStatusTrait;

  protected function defaultLabel() {
    return t('@name (@id)', ['@name' => $this->name, '@id' => $this->id]);
  }

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_product');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    return parent::save();
  }

  function standards() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'shusy_product_standard');
    $query->propertyCondition('product_id', $this->id);
    $query->propertyOrderBy('id');
    $result = $query->execute();
    $ids = [];
    if (!empty($result)) {
      foreach ($result['shusy_product_standard'] as $item) {
        $ids[] = $item->id;
      }
    }
    return entity_load('shusy_product_standard', $ids);
  }

  function price() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'shusy_product_standard');
    $query->propertyCondition('product_id', $this->id);
    $query->propertyCondition('status', 1);
    $query->propertyOrderBy('amount', 'ASC');
    $query->propertyOrderBy('id');
    $query->range(0, 1);
    $result = $query->execute();
    if (!empty($result)) {
      foreach ($result['shusy_product_standard'] as $item) {
        return shusy_product_standard_load($item->id);
      }
    }
    //如果商品不存在上架的规格 会出错
    return new ShusyProductStandard();
  }
}
